<?php

$xml = simplexml_load_file('bw.xml');
$body = $xml->body;

try {
	$dbh = 
		new PDO("pgsql:dbname=relex;host=localhost;user=relex;password=relex");

	$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$dbh->beginTransaction();


	$q_doc = $dbh->prepare(
		"INSERT INTO lexdoc(doctype_id, pubdate) " .
		"VALUES(?, ?)");
	$q_part = $dbh->prepare(
		"INSERT INTO lexpart(doc_id, parttype_id, partno, seqno, validfrom) " .
		"VALUES(?, ?, ?, ?, ?)");
	$q_text = $dbh->prepare(
		"INSERT INTO lexparttext(part_id, language, body) " .
		"VALUES(?, ?, ?)");

	$q_doc->execute(array(1, '1830-01-01'));
	$docid = $dbh->lastInsertid('lexdoc_id_seq');
	print "Inserted LAW as " . $docid . "\n";
	
	$dbh->commit();

	print "new";
	$dbh->beginTransaction();

	$seqno = 0;

	foreach($body->section as $section) {
		$meta = $section->div[0];
		$level = (int) $meta['class'];
		$partno = $meta[0];
		$body = $section->div[1]->asXML();

		$seqno++;
		$q_part->execute(
			array($docid, $level + 2, $partno, $seqno, '1830-01-01'));

		$partid = $dbh->lastInsertId('lexpart_id_seq');

		$q_text->execute(
			array($partid, 'nl', $body));

		print "Inserted $partno as $partid \n";
	}

	$dbh->commit();
} catch (PDOException $e) {
	print "Error " . $e->getMessage();
	$dbh->rollback();
}

$dbh = null;

